let fs = require('fs');
let { resolve } = require('path');
let uuid = require('uuid');
let id = 0;

class Node {
  constructor(name, parent) {
    this.id = id++;
    this.name = name;
    this.parentNode = parent;
    this.childrenNodeList = [];
    this.notNull = false;
    this.path = null;
  }
  set parentNode(node) {
    if (node != null) {
      this.parent = node;
      this.parentName = node.name;
    }
  }
  get parentNode() {
    return this.parent;
  }
  push(...args) {
    args.forEach(item => {
      item.parentNode = this;
    });
    return this.childrenNodeList.push(...args)
  }
  toJSON() {
    let { id, path, name, children } = this;
    if (this.childrenNodeList.length != 0) {
      children = this.childrenNodeList
    }
    return {
      id,
      path,
      name,
      children
    }
  }
}

let readDirDep = (name, path, config) => {
  // 初始化
  let node = new Node(name);
  let a = fs.readdirSync(path);
  a.forEach(file => {
    var director = resolve(path, file);
    let st = fs.statSync(director);
    if (st.isDirectory()) {
      let childrenNode = readDirDep(file, director, config)
      if (childrenNode.notNull) {
        node.notNull = true;
        node.push(childrenNode);
      }
    }
    if (st.isFile()) {
      if (config.test instanceof RegExp) {
        if (!config.test.test(director)) {
          return;
        }
      }
      if (config.test instanceof Function) {
        if (!config.test(director)) {
          return;
        }
      }
      let childrenNode = new Node(file);
      let ss = file.split(/\./);
      if (ss[0] == "index") {
        childrenNode.path = "";
      } else {
        childrenNode.path = ss[0];
      }
      node.notNull = true;
      node.push(childrenNode);
    }
  })
  if (path == "index") {
    node.path = "";
  } else {
    node.path = path;
  }
  return node;
}

let a = function (source) {
  let jsStr = new String(source);
  let obj = eval(jsStr.toString());
  let reg = /.*\.vue$/;
  console.log(reg instanceof RegExp)
  // let callback = this.async();
  let path = resolve(__dirname, "..", obj.basePath);
  let node = readDirDep(obj.basePath, path, {
    test: reg
  });
  console.log(JSON.stringify(node, null, 2));
};

a("exports = {basePath:'src/views'}")

exports = a;


